package crowdflower;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import org.apache.commons.lang.xwork.StringEscapeUtils;

import util.io.FileOutput;



import model.db.Query;
import model.db.Vertical;
import model.db.VerticalResult;
import contact.controller.QueryManager;
import contact.controller.VerticalManager;
import contact.controller.VerticalResultsManager;
import contact.view.util.Comparissons;
import contact.view.util.SurveyLogic;

public class GenerateCrowdFlowerData {

	
	QueryManager queryManager;
	VerticalManager verticalManager;
	
	boolean againtsGoogle= true;
	VerticalResultsManager resultsManager;
	String path="";
	
	public String blank_image="http://wwwhome.cs.utwente.nl/~duartes/images/filling_small.png";
	
	public GenerateCrowdFlowerData(String path){
		
		verticalManager = new VerticalManager();
		queryManager= new QueryManager();
		resultsManager= new VerticalResultsManager();
		this.path=path;
	}
	
	public void generateCrownFlowerData(int rank_limit){
		List<Query> queries = queryManager.list();
		
		for(int i =0; i < queries.size();i++){
			
			Query q= queries.get(i);
			generateDataForQuery(q,rank_limit);
		
		}
		
	}

	private void generateDataForQuery(Query q, int MAX_RANK) {
		// TODO Auto-generated method stub
		long query_id = q.getId();
		 List<VerticalResult> results = resultsManager.getVerticalResults(query_id, MAX_RANK);
		 Hashtable<Long, ArrayList<VerticalResult>> organized =resultsManager.getVerticalResultsOrganized(results);
 		 ArrayList<ArrayList<VerticalResult>> organized_list = resultsManager.toList(organized);
		 Comparissons compa = new Comparissons(againtsGoogle, organized_list,organized);
		 printUnits(compa,organized,q);
	}

	
	/**
	 * Print evaluation units in the following format
	 * 
	 * 
	 * query   query_id  left_ver_name  left_ver_id right_ver  right_ver_id html
	 * 
	 * @param compa
	 * @param organized
	 * @param q
	 */
	private void printUnits(Comparissons compa,
			Hashtable<Long, ArrayList<VerticalResult>> organized, Query  q) {
		// TODO Auto-generated method stub
		FileOutput out =new FileOutput(path);
		
		String texto="query,query_id,left_ver_name,left_ver_id,right_ver,right_ver_id,content_html\n";
		
		for(int i =0; i<compa.sequence.size();i++){
			
		 long[] ids = compa.sequence.get(i);
		  
		 Vertical left = verticalManager.getVertical(ids[0]);
		 Vertical right = verticalManager.getVertical(ids[1]);
		
		 String type_left = SurveyLogic.classifyResultType(left);
		 String type_right = SurveyLogic.classifyResultType(right);
		  
		 ArrayList<VerticalResult> results_left = organized.get(ids[0]);
		 ArrayList<VerticalResult> results_right = organized.get(ids[1]);
	
		 String html_content_left = generateHTMLResults(results_left,type_left);
		 String html_content_right = generateHTMLResults(results_right,type_right);
		 String html = generateHTML(html_content_left, html_content_right, "" );
		 
		 String output=escapeCVSString(q.getQuery())+ ","+ escapeCVSString(String.valueOf(q.getId())) + ","+  escapeCVSString(left.getName()) + ","+ escapeCVSString(String.valueOf(left.getId())) + ","+ escapeCVSString(right.getName()) + ","+ escapeCVSString(String.valueOf(right.getId())) + ","+ escapeCVSString(html);
		 
		 texto= texto+ output +"\n";
 
		 System.out.println(output);
		}
		out.createFile(path,texto);

	}

	public String escapeCVSString(String s){
		
		
		String t=StringEscapeUtils.escapeCsv(s);
		
		
		return t;
		
	
	}
	
	private String generateHTML(String left, String right, String header){
	
		String t= header + " <table width=\"85%\" class=\"table_spacing\"> "+
		"		<TR> "+
	 	"		<TD width=\"40%\" class=\"vertaligntop\"> "+
        "         <table id=\"web_results\" class=\"sample\"> "+
		"		 <col style=\"padding-right:20px;\" /> "+
		"		    <col style=\"padding-right:20px;\" />" +
		
		left + 
    	"	</table> "+
		"		</td> "+
		"		<td width=\"10%\" class=\"vertaligntop\"></td> "+
		"		<TD width=\"45%\" class=\"vertaligntop\">"+
  		" <table id=\"right_results\" class=\"sample\"  border=\"1\"> "+
		"		 <col style=\"padding-right:20px;\" /> "+
		"		    <col style=\"padding-right:20px;\" /> "+
  	    right+
		"	</table> "+
        "	</TD> "+
		"		</TR> "+
		"		</table> ";
		
		
		
		t= t.replaceAll("\\s+", " ");
		
		return t;
		
	}
	
	
	private String generateHTMLResults(ArrayList<VerticalResult> results_left,
			String type_left) {
		// TODO Auto-generated method stub
		String t="";
		for(int i =0; i<results_left.size(); i++){
			VerticalResult current= results_left.get(i);
			
			t= t+"<tr>";
			if(!current.getThumbnail().equals("")){
				
				t= t+ "	<td align=\"center\" class=\"vertalignmiddle\">  "+
				      "<img  id=\"scale-down\" style=\"height: 80px\" src=\"" + current.getThumbnail()+"\" alt=\"Thumbnail\" onerror=\"this.src='"+ blank_image+"';\"/>  "+
			          " <br> <br> "+
						" </td> "+
					" <td width=\"2%\" align=\"center\" valign=\"middle\">  </td>";	
			}
		t= t+"<td>  "+
		"<table class=\"table_spacing2\" > ";
	
		if(type_left !=null && type_left.equals(SurveyLogic.IMAGE_VERTICAL)){
			
		t=t+	" <tr>  "+
			  		"		<td> "+
			  			"		<div id=\"scale-down\" style=\"height: 160px\"> "+
			  			"			<a href=\""+ current.getUrl()   +"\"><img src=\""+ current.getUrl()   +"\" alt=\""+current.getTitle()  +"\"></a>  "+
						"		</div>  "+
			  			"		<br><br> "+
						"	</td>  "+
			    " </tr>  ";
		}else{
		  t= t +"<tr> "+
				"	  <td> "+
					 
	        	"		<a class=\"result_title\" href=\""+ current.getUrl() + "\" class=\"result_title\">"+ current.getTitle() +"</a> "+
	       		"		</td>  "+
	          	"	</tr> "+
	        	"	<tr>  "+
	             "     <td> <div class=\"result_url\">"+current.getUrl()+"</div> </td>  "+
	           	"	 </tr>  "+
			   	"	<tr> "+
	             " 		 <td> <div class=\"result_snippet\">"+current.getSnippet() +"</div><br>"+
	             "  	</td>   "+
				"	</tr>  ";
			
		}
		
	t= t+ "  </table> "+
		"</td> "+
		"</tr>	 ";
		}	
		return t;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		String path="/Users/sergioduarte/Documents/crowd_flower_data.csv";

		GenerateCrowdFlowerData generator = new GenerateCrowdFlowerData(path);
		
		
		String prueba="asdfasdfasadsfafas, asdasdf asdfaasdfassd";
		
		
		//System.out.println(prueba);
		
	//	System.out.println(generator.escapeCVSString(prueba));
		generator.generateCrownFlowerData(4);
	
		
	}
	
	
	
	
	

}
